package org.luxor.sdk.common;

import com.google.gson.reflect.TypeToken;
import org.luxor.sdk.auth.v1.AccessToken;
import org.luxor.sdk.common.exception.LuxorCloudSDKException;
import org.luxor.sdk.common.models.ResponseModel;
import org.luxor.sdk.common.profile.ClientProfile;
import org.luxor.sdk.common.profile.HttpMethod;

import java.lang.reflect.Type;
import java.util.HashMap;

/**
 * 用户级客户端
 *
 * @author Mr.yan  @date 2021/9/13
 */
public class CommonUserClient extends AbstractClient {

    @Override
    public AccessToken getAuthorization(HashMap<String, String> headers, byte[] bodyPayload) throws LuxorCloudSDKException {
        if (accessToken != null && accessToken.expiresTimeMs != 0 && accessToken.expiresTimeMs < System.currentTimeMillis()) {
            return accessToken;
        }
        String url = getClientProfile().getHttpProfile().getUrl() + "/login";
        HashMap<String, String> params = new HashMap<>();
        params.put("username", "admin");
        params.put("password", "luxor@123");
        String canonicalQueryString = formatQueryParams(params, bodyPayload);
        String respBody = getResponseBody(HttpMethod.POST, url + "?" + canonicalQueryString, headers, bodyPayload);
        Type errType = new TypeToken<ResponseModel<AccessToken>>() {
        }.getType();
        ResponseModel<AccessToken> errResp = gson.fromJson(respBody, errType);
        if (errResp.data.expiresTimeMs == 0 && errResp.data.expiresIn != 0) {
            errResp.data.expiresTimeMs = System.currentTimeMillis() + errResp.data.expiresIn * 1000;
        }
        return errResp.data;
    }

    public CommonUserClient(String version, Credential credential) {
        this(version, credential, "global", new ClientProfile());
    }

    public CommonUserClient(String version, Credential credential, String region) {
        this(version, credential, region, new ClientProfile());
    }

    public CommonUserClient(String version, Credential credential, String region, ClientProfile profile) {
        super(version, credential, region, profile);
    }

}